package com.example.mrzhou.lvmm.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Mr.zhou on 2016/10/27.
 */
public class RetroManager {

    private static volatile RetroManager instance = null;
    private static Retrofit retrofit;

    OkHttpClient client;
    private static final int DEFAULT_READ_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_WRITE_TIMEOUT = 15 * 1000;

    private RetroManager(String baseUrl) {
        initOkhttpClient();
        initRetrofit(baseUrl);
    }

    public static RetroManager getInstance(String baseUrl) {
        if (instance == null) {
            synchronized (RetroManager.class) {
                if (instance == null) {
                    instance = new RetroManager(baseUrl);
                }
            }
        }
        return instance;
    }

    private void initRetrofit(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(client)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }
    }

    private void initOkhttpClient() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        }
    }

    private Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
//                .setDateFormat("yyyy-MM-dd")//设置日期格式
                .create();
    }

    public SurroundService getSurService() {
        return retrofit.create(SurroundService.class);
    }

    public HomeService getHomeService() {
        return retrofit.create(HomeService.class);
    }

    public TMService getTMService() {
        return retrofit.create(TMService.class);
    }

    public DesService getDesService() {
        return retrofit.create(DesService.class);
    }

}

